package com.zhongxi.guoyuan.fragment.cartstore;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.graphics.drawable.ColorDrawable;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.text.Html;
import android.text.TextUtils;
import android.view.Display;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.google.gson.Gson;
import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshListView;
import com.zhongxi.guoyuan.R;
import com.zhongxi.guoyuan.adapter.coinShop.CoinPostGoodAttrAdapter;
import com.zhongxi.guoyuan.adapter.rewardCoin.RewardShoppingCartAdapter;
import com.zhongxi.guoyuan.application.MyApplication;
import com.zhongxi.guoyuan.base.BaseFragment;
import com.zhongxi.guoyuan.entity.BaseResponse;
import com.zhongxi.guoyuan.entity.coinStore.AttrItemBean;
import com.zhongxi.guoyuan.entity.coinStore.AttrsSelect;
import com.zhongxi.guoyuan.entity.coinStore.DouGoodsData;
import com.zhongxi.guoyuan.entity.coinStore.GoodsAttrCollections;
import com.zhongxi.guoyuan.entity.coinStore.ItemGoodAttr;
import com.zhongxi.guoyuan.entity.coinStore.ItemGoodCollectionInfo;
import com.zhongxi.guoyuan.entity.coinStore.PostCartAllAttrs;
import com.zhongxi.guoyuan.entity.coinStore.PostCartDel;
import com.zhongxi.guoyuan.entity.coinStore.PostItemGoodShopCartInfo;
import com.zhongxi.guoyuan.entity.coinStore.PostShopCartInfo;
import com.zhongxi.guoyuan.entity.coinStore.PostShopingCart;
import com.zhongxi.guoyuan.entity.coinStore.PostcartAttrsCollection;
import com.zhongxi.guoyuan.entity.coinStore.SelcetPostCartGoodsAttrs;
import com.zhongxi.guoyuan.entity.coinStore.ShopInfos;
import com.zhongxi.guoyuan.url.Url;
import com.zhongxi.guoyuan.utils.CommonTool;
import com.zhongxi.guoyuan.utils.DataUtil;
import com.zhongxi.guoyuan.view.rewardCoin.ApplyRewardActivity;
import com.zhongxi.guoyuan.view.shopCart.ShoppingCartActivity;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;

import static com.baidu.location.d.g.e;

/**
 * Created by Administrator on 2017/10/26.
 */
@SuppressLint("ValidFragment")
public class PostStoreFragment extends BaseFragment {

    private Handler postHandler;
    private static final int RESULTACCOUNTS = 50;
    @Bind(R.id.ptr_listView)
    PullToRefreshListView ptrListView;
    @Bind(R.id.tv_reward_price)
    TextView tvRewardPrice;
    @Bind(R.id.tv_hd)
    TextView tvHd;
    @Bind(R.id.tv_md)
    TextView tvMd;
    @Bind(R.id.tv_total_postage)
    TextView tvTotalPostage;
    @Bind(R.id.tv_all_select)
    TextView tvAllSelect;
    @Bind(R.id.tv_accounts)
    TextView tvAccounts;
    @Bind(R.id.relaBottom)
    LinearLayout relaBottom;
    private RewardShoppingCartAdapter postCartAdapter;
    private List<Object> list = new ArrayList<>();
    private List<ShopInfos> keyList = new ArrayList<>();
    private List<String> amountofmaillist = new ArrayList<>();
    private String type;

    private SelcetPostCartGoodsAttrs item;
    private List<GoodsAttrCollections> attrCollectionses;
    private ArrayList<String> attrKeyList;
    private JSONObject attr;
    private Map<String, List<String>> map;
    private List<List<AttrItemBean>> itemAttrList;
    private Map<String, List<AttrItemBean>> mapAllAttrs;
    private List<String> keyLists;
    private ArrayList<AttrsSelect> allList;

    private View popupWindow_view;
    private PopupWindow popupWindow;
    private ImageView ivImg;
    private boolean isRemove;
    private CoinPostGoodAttrAdapter coinPostGoodAttrAdapter;
    private boolean isSameAttrKey;
    private List<SelcetPostCartGoodsAttrs> selectGoodsList = new ArrayList<>();

    private TextView tvInventory;
    private TextView tvPostage;
    private TextView tv_edit_hd;
    private TextView tv_edit_md;

    Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            position = (int) msg.obj;
            switch (msg.what) {
                case 0:
                    if (null != popupWindow && popupWindow.isShowing()) {
                        popupWindow.dismiss();
                        return;
                    } else {
                        getGoodAttrs();
                    }
                    break;
                case 1:
                    detail();
                    break;
                case 2:    //减少
                    updateStoreNum();
                    break;
                case 3: //增多
                    updateStoreNum();
                    break;
            }

        }
    };
    private JSONObject goodsInfoObject;
    private List<PostcartAttrsCollection> datas;
    private TextView tv_edit_price;
    private int position;
    private Map<String, List<SelcetPostCartGoodsAttrs>> mapAll;

    public PostStoreFragment(Handler postHandler) {
        this.postHandler = postHandler;
    }

    private void getGoodAttrs() {
        item = (SelcetPostCartGoodsAttrs) list.get(position);
        String str = "&gid=" + item.getGoodsid();
        type = "goodAttr";
        getServer(Url.GOOD_ATTR, null, str, false, null, "get");
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_post_cart, container, false);
        ButterKnife.bind(this, view);
        return view;
    }

    @Override
    protected void initView() {
        super.initView();
        tvTotalPostage.setVisibility(View.VISIBLE);
        getData();
    }

    private void getData() {
        type = "shoplist";
        String str = "&getermethod=1";
        getServer(Url.MY_SHOPCART, null, str, false, null, "get");
    }

    @Override
    protected void initData() {
        super.initData();
        getDataEmpty();
    }

    private void getDataEmpty() {
        TextView tv = new TextView(context);
        tv.setGravity(Gravity.CENTER);
        tv.setText("亲,您的购物车还没添加商品哟!");
        tv.setTextSize(20);
        //当界面为空的时候显示的视图
        ptrListView.setEmptyView(tv);
    }

    @OnClick({R.id.tv_all_select, R.id.tv_accounts})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.tv_all_select:
                if (list != null && list.size() > 0) {
                    postCartAdapter.setAllChecked(!postCartAdapter.isAllChecked());
                    for (int i = 0; i < list.size(); i++) {
                        if (!keyList.contains(list.get(i)) && !amountofmaillist.contains(list.get(i))) {
                            SelcetPostCartGoodsAttrs goodsAttrs = (SelcetPostCartGoodsAttrs) list.get(i);
                            if (goodsAttrs.getStatus().equals("0") || goodsAttrs.getItemStatus().equals("0") || goodsAttrs.getItemGoodAttrs() == null
                                    || goodsAttrs.getItemGoodAttrs().size() == 0 || "0".equals(goodsAttrs.getStocknum()) || goodsAttrs.getStocknum() == null) {
                                goodsAttrs.setSelected(false);
                            } else {
                                if (postCartAdapter.isAllChecked()) {
                                    goodsAttrs.setSelected(true);
                                } else {
                                    goodsAttrs.setSelected(false);
                                }
                            }
                        }
                    }
                    postCartAdapter.notifyDataSetChanged();
                    updateAmount();
                } else {
                    showShortToast("购物车暂无数据");
                }
                break;
            case R.id.tv_accounts:  //结算
                if (updateAmount() == null || "".equals(updateAmount()) || updateAmount().equals("}")) {
                    showShortToast("请选择商品");
                } else {
                    List<SelcetPostCartGoodsAttrs> selectGoodsAttrList = new ArrayList<>();
                    for (int i = 0; i < list.size(); i++) {
                        if (!keyList.contains(list.get(i)) && !amountofmaillist.contains(list.get(i))) {
                            SelcetPostCartGoodsAttrs goodsAttrs = (SelcetPostCartGoodsAttrs) list.get(i);
                            if (goodsAttrs.isSelected()) {
                                selectGoodsAttrList.add(goodsAttrs);  //总勾择
                            }
                        }
                    }
                    ArrayList<PostcartAttrsCollection> collectionList = new ArrayList<>();
                    for (int j = 0; j < datas.size(); j++) {
                        PostcartAttrsCollection postcartAttrsCollection = datas.get(j);
                        List<SelcetPostCartGoodsAttrs> selectGoodsList = new ArrayList<>();
                        for (int i = 0; i < postcartAttrsCollection.getGoodsAttrses().size(); i++) {
                            SelcetPostCartGoodsAttrs goodsAttrs = postcartAttrsCollection.getGoodsAttrses().get(i);
                            for (int k = 0; k < selectGoodsAttrList.size(); k++) {
                                if (selectGoodsAttrList.get(k).getGoodId().equals(goodsAttrs.getGoodId())) {
                                    selectGoodsList.add(selectGoodsAttrList.get(k));  //每一个店铺商品的勾选
                                }
                            }
                        }
                        PostcartAttrsCollection attrsCollection = new PostcartAttrsCollection();
                        if (selectGoodsList.size() > 0) {
                            for (int i = 0; i < list.size(); i++) {
                                if (keyList.contains(list.get(i))) {
                                    ShopInfos shopInfos = (ShopInfos) list.get(i);
                                    if (postcartAttrsCollection.getShopInfos().getName().equals(shopInfos.getName())) {
                                        attrsCollection.setShopInfos(shopInfos);
                                    }
                                }
                            }
                            attrsCollection.setGoodsAttrses(selectGoodsList);
                            collectionList.add(attrsCollection);
                        }
                    }
                    Intent intentApply = new Intent(context, ApplyRewardActivity.class);
                    Bundle bundle = new Bundle();
                    bundle.putSerializable("goodsList", collectionList);
                    bundle.putInt("post", 1);
                    intentApply.putExtras(bundle);
                    startActivityForResult(intentApply, RESULTACCOUNTS);
                }
                break;
        }
    }

    @Override
    protected void initEvent() {
        super.initEvent();
        ptrListView.setOnRefreshListener(new PullToRefreshBase.OnRefreshListener<ListView>() {
            @Override
            public void onRefresh(PullToRefreshBase<ListView> refreshView) {
                getData();
            }
        });
    }

    @Override
    protected void processSuccessResult(String response) {
        super.processSuccessResult(response);
        try {
            Gson gson = new Gson();
            if ("shoplist".equals(type)) {
                PostShopingCart postShopingCart = gson.fromJson(response, PostShopingCart.class);
                MyApplication.getInstance().setSpValue(postShopingCart.getSafeobj());
                if (postShopingCart.getShopInfo() != null && postShopingCart.getShopInfo().size() > 0) {
                    List<ShopInfos> shopInfo = postShopingCart.getShopInfo();
                    JSONObject jsonObject = new JSONObject(response);
                    JSONObject collectionInfoObject = jsonObject.optJSONObject("collectionInfo");
                    goodsInfoObject = jsonObject.optJSONObject("goodsInfo");
                    JSONObject parseAttrObject = jsonObject.optJSONObject("parseAttr");
                    JSONObject selAttrObject = jsonObject.optJSONObject("selAttr");
                    JSONObject shopCartObject = jsonObject.optJSONObject("shopCart");
                    List<PostCartAllAttrs> allDatas = new ArrayList<>();
                    for (int i = 0; i < shopInfo.size(); i++) {
                        PostCartAllAttrs postCartAllAttrs = new PostCartAllAttrs();
                        ShopInfos shopInfos = shopInfo.get(i);
                        List<PostShopCartInfo> postShopCartInfos = new ArrayList<>();
                        if (shopCartObject != null && !"".equals(shopCartObject)) {
                            JSONArray jsonArray = shopCartObject.optJSONArray(shopInfos.getId());
                            for (int j = 0; j < jsonArray.length(); j++) {
                                PostShopCartInfo shopCartInfo = PostShopCartInfo.parseMatch((JSONObject) jsonArray.get(j));
                                postShopCartInfos.add(shopCartInfo);
                            }
                        }
                        postCartAllAttrs.setShopInfos(shopInfos);
                        postCartAllAttrs.setPostShopCartInfos(postShopCartInfos);
                        allDatas.add(postCartAllAttrs);
                    }
                    datas = new ArrayList<>();
                    mapAll = new HashMap<>();
                    if (goodsInfoObject != null && !"".equals(goodsInfoObject)) {
                        for (int i = 0; i < allDatas.size(); i++) {
                            PostcartAttrsCollection postcartAttrsCollection = new PostcartAttrsCollection();
                            List<PostShopCartInfo> postShopCartInfos = allDatas.get(i).getPostShopCartInfos();
                            List<SelcetPostCartGoodsAttrs> selectGoodsAttrs = new ArrayList<>();
                            String storeNum = "0";
                            for (int j = 0; j < postShopCartInfos.size(); j++) {
                                PostShopCartInfo shopCartInfo = postShopCartInfos.get(j);
                                if (goodsInfoObject.optJSONObject(shopCartInfo.getGoodsid()) != null && !"".equals(goodsInfoObject.optJSONObject(shopCartInfo.getGoodsid()))) {
                                    SelcetPostCartGoodsAttrs goodsAttrs = new SelcetPostCartGoodsAttrs();
                                    if (shopCartInfo.getId() != null && !"".equals(shopCartInfo.getId())) {
                                        goodsAttrs.setGoodId(shopCartInfo.getId());
                                    }
                                    if (shopCartInfo.getAttrcollection() != null && !"".equals(shopCartInfo.getAttrcollection())) {
                                        goodsAttrs.setAttrcollection(shopCartInfo.getAttrcollection());
                                    }
                                    if (shopCartInfo.getGoodsid() != null && !"".equals(shopCartInfo.getGoodsid())) {
                                        goodsAttrs.setGoodsid(shopCartInfo.getGoodsid());
                                    }
                                    if (shopCartInfo.getGoodsnum() != null && !"".equals(shopCartInfo.getGoodsnum())) {
                                        goodsAttrs.setGoodsnum(shopCartInfo.getGoodsnum());
                                        storeNum = DataUtil.add(storeNum, shopCartInfo.getGoodsnum());
                                    }
                                    if (shopCartInfo.getGetermethod() != null && !"".equals(shopCartInfo.getGetermethod())) {
                                        goodsAttrs.setGetermethod(shopCartInfo.getGetermethod());
                                    }
                                    PostItemGoodShopCartInfo itemGoodShopCartInfo = PostItemGoodShopCartInfo.parseMatch(goodsInfoObject.optJSONObject(shopCartInfo.getGoodsid()));
                                    if (itemGoodShopCartInfo.getName() != null && !"".equals(itemGoodShopCartInfo.getName())) {
                                        goodsAttrs.setName(itemGoodShopCartInfo.getName());
                                    }
                                    if (itemGoodShopCartInfo.getPostage() != null && !"".equals(itemGoodShopCartInfo.getPostage())) {
                                        goodsAttrs.setPostage(itemGoodShopCartInfo.getPostage());
                                    }
                                    if (!TextUtils.isEmpty(itemGoodShopCartInfo.getGoodstype())) {
                                        goodsAttrs.setGoodstype(itemGoodShopCartInfo.getGoodstype());
                                    }
                                    if (itemGoodShopCartInfo.getOrdernum() != null && !"".equals(itemGoodShopCartInfo.getOrdernum())) {
                                        goodsAttrs.setOrdernum(itemGoodShopCartInfo.getOrdernum());
                                    }
                                    if (!TextUtils.isEmpty(itemGoodShopCartInfo.getStatus())) {
                                        goodsAttrs.setItemStatus(itemGoodShopCartInfo.getStatus());
                                    }
                                    if (shopCartInfo.getAttrcollection() != null && !"".equals(shopCartInfo.getAttrcollection())) {
                                        if (null != collectionInfoObject && !"".equals(collectionInfoObject)) {
                                            if (collectionInfoObject.optJSONObject(shopCartInfo.getAttrcollection()) != null && !"".equals(collectionInfoObject.optJSONObject(shopCartInfo.getAttrcollection()))) {
                                                ItemGoodCollectionInfo collectionInfo = ItemGoodCollectionInfo.parseMatch(collectionInfoObject.optJSONObject(shopCartInfo.getAttrcollection()));
                                                if (collectionInfo.getThumbnail() != null && !"".equals(collectionInfo.getThumbnail())) {
                                                    goodsAttrs.setImgUrl(collectionInfo.getThumbnail());
                                                }
                                                if (collectionInfo.getPrice() != null && !"".equals(collectionInfo.getPrice())) {
                                                    goodsAttrs.setPrice(collectionInfo.getPrice());
                                                }
                                                if (collectionInfo.getStocknum() != null && !"".equals(collectionInfo.getStocknum())) {
                                                    goodsAttrs.setStocknum(collectionInfo.getStocknum());
                                                }
                                            }
                                        }
                                    }
                                    List<ItemGoodAttr> itemGoodAttrs = new ArrayList<>();
                                    if (selAttrObject != null && !"".equals(selAttrObject)) {
                                        JSONArray jsonArray = selAttrObject.optJSONArray(shopCartInfo.getId());
                                        for (int k = 0; k < jsonArray.length(); k++) {
                                            JSONObject objectItemAttr = parseAttrObject.optJSONObject((String) jsonArray.get(k));
                                            ItemGoodAttr itemGoodAttr = ItemGoodAttr.parseMatch(objectItemAttr);
                                            itemGoodAttrs.add(itemGoodAttr);
                                        }
                                    }
                                    goodsAttrs.setItemGoodAttrs(itemGoodAttrs);
                                    selectGoodsAttrs.add(goodsAttrs);
                                }
                            }
                            postcartAttrsCollection.setShopInfos(allDatas.get(i).getShopInfos());
                            postcartAttrsCollection.setGoodsAttrses(selectGoodsAttrs);
                            postcartAttrsCollection.setStoreNum(storeNum);
                            mapAll.put(allDatas.get(i).getShopInfos().getName(), selectGoodsAttrs);
                            datas.add(postcartAttrsCollection);
                        }
                        list.clear();
                        keyList.clear();
                        amountofmaillist.clear();
                        for (int i = 0; i < datas.size(); i++) {
                            ShopInfos shopInfos = datas.get(i).getShopInfos();
                            list.add(shopInfos);
                            String status = shopInfos.getStatus();
                            shopInfos.setStoreNum(datas.get(i).getStoreNum());
                            keyList.add(shopInfos);
                            List<SelcetPostCartGoodsAttrs> goodsAttrses = datas.get(i).getGoodsAttrses();
                            String totalPost = "0";
                            for (int j = 0; j < goodsAttrses.size(); j++) {
                                SelcetPostCartGoodsAttrs goodsAttrs = goodsAttrses.get(j);
                                totalPost = DataUtil.add(goodsAttrs.getPostage(), totalPost);
                                goodsAttrs.setStatus(status);
                                list.add(goodsAttrs);
                            }
                            if (DataUtil.moreThanZero(shopInfos.getAmountofmail())) {
                                list.add("本店满" + shopInfos.getAmountofmail() + "元包邮");
                                amountofmaillist.add("本店满" + shopInfos.getAmountofmail() + "元包邮");
                            } else if (!DataUtil.moreThanZero(totalPost)) {
                                list.add("本店包邮");
                                amountofmaillist.add("本店包邮");
                            } else {
                                list.add("本店不包邮");
                                amountofmaillist.add("本店不包邮");
                            }
                        }
                        postCartAdapter = new RewardShoppingCartAdapter(context, this, list, keyList, amountofmaillist, handler);
                        ptrListView.setAdapter(postCartAdapter);
                    } else {
                        list.clear();
                        keyList.clear();
                        amountofmaillist.clear();
                        if (postCartAdapter != null) {
                            postCartAdapter.notifyDataSetChanged();
                        }
                    }
                } else {
                    Message msg = Message.obtain();
                    msg.what = 1;
                    msg.obj = "null";
                    postHandler.sendMessage(msg);
                    list.clear();
                    if (postCartAdapter != null) {
                        postCartAdapter.notifyDataSetChanged();
                    }
                }
                ptrListView.onRefreshComplete();
                updateAmount();  //处理选中删除的数据
            } else if ("goodAttr".equals(type)) {
                DouGoodsData postGoodsData = gson.fromJson(response, DouGoodsData.class);
                MyApplication.getInstance().setSpValue(postGoodsData.getSafeobj());
                if (postGoodsData.getGoodsAttrCollection() != null && !"".equals(postGoodsData.getGoodsAttrCollection())) {
                    attrCollectionses = postGoodsData.getGoodsAttrCollection();
                    attrKeyList = postGoodsData.getAttrKey();
                    JSONObject jsonObject = new JSONObject(response);
                    attr = jsonObject.optJSONObject("attrList");
                    //key :属性类 values:属性类下属性的所有的id值
                    map = new HashMap<>();
                    itemAttrList = new ArrayList<>();
                    if (attr != null && !"".equals(attr)) {
                        Iterator<String> keys = attr.keys();
                        mapAllAttrs = new HashMap<>();
                        keyLists = new ArrayList<>();
                        while (keys.hasNext()) {
                            String next = keys.next();
                            keyLists.add(next);
                            JSONArray jsonArray = attr.optJSONArray(next);
                            List<String> attrIdList = new ArrayList<>();
                            List<AttrItemBean> itemList = new ArrayList<>();
                            for (int i = 0; i < jsonArray.length(); i++) {
                                JSONArray jsonArray1 = (JSONArray) jsonArray.get(i);
                                AttrItemBean attrItemBean = new AttrItemBean();
                                String attrname = (String) jsonArray1.get(0);
                                attrItemBean.setName(attrname);
                                String attrid = (String) jsonArray1.get(1);
                                attrItemBean.setAttrId(attrid);
                                attrIdList.add(attrid);
                                List<ItemGoodAttr> itemGoodAttrs = item.getItemGoodAttrs();
                                for (int l = 0; l < itemGoodAttrs.size(); l++) {
                                    if (itemGoodAttrs.get(l).getId().equals(attrid)) {
                                        attrItemBean.setStates("0");     //选中
                                        break;
                                    } else {
                                        attrItemBean.setStates("1");
                                    }
                                }
                                itemList.add(attrItemBean);
                            }
                            map.put(next, attrIdList);
                            itemAttrList.add(itemList);
                            mapAllAttrs.put(next, itemList);
                        }
                    }
                    allList = new ArrayList<>();
                    JSONArray jsonArray2 = jsonObject.optJSONArray("goodsAttrCollection");
                    for (int i = 0; i < jsonArray2.length(); i++) {
                        Map<String, List<String>> itemAttrMap = new HashMap<>();
                        JSONObject jsonObject1 = (JSONObject) jsonArray2.get(i);
                        AttrsSelect attrsSelect = new AttrsSelect();
                        String price = jsonObject1.optString("price");
                        String thumbnail = jsonObject1.optString("thumbnail");
                        String goodsid = jsonObject1.optString("goodsid");
                        String id = jsonObject1.optString("id");
                        String stocknum = jsonObject1.optString("stocknum");
                        JSONObject object = jsonObject1.optJSONObject("newattr");
                        if (object != null && !"".equals(object)) {
                            Iterator<String> keys = object.keys();
                            while (keys.hasNext()) {
                                String next = keys.next();
                                JSONArray jsonArray = object.optJSONArray(next);
                                List<String> attrItem = new ArrayList<>();
                                if (jsonArray != null && jsonArray.length() > 0) {
                                    for (int j = 0; j < jsonArray.length(); j++) {
                                        attrItem.add((String) jsonArray.get(j));
                                    }
                                    itemAttrMap.put(next, attrItem);
                                }
                            }
                        }
                        attrsSelect.setPrice(price);
                        attrsSelect.setThumbnail(thumbnail);
                        attrsSelect.setItemMaps(itemAttrMap);
                        attrsSelect.setGoodsid(goodsid);
                        attrsSelect.setId(id);
                        attrsSelect.setStocknum(stocknum);
                        allList.add(attrsSelect);
                    }
                    initPopupWindow();
                }
            } else if ("editcart".equals(type)) {
                BaseResponse baseResponse = gson.fromJson(response, BaseResponse.class);
                MyApplication.getInstance().setSpValue(baseResponse.getSafeobj());
                showShortToast("属性编辑成功");
                popupWindow.dismiss();
                isRemove = false;
                popupWindow = null;
            } else if ("del".equals(type)) {
                PostCartDel postCartDel = gson.fromJson(response, PostCartDel.class);
                MyApplication.getInstance().setSpValue(postCartDel.getSafeobj());
                showShortToast("删除成功,共删除购物车" + postCartDel.getItemNum() + "件条目");
//                List<List<ItemGoodAttr>> lists = new ArrayList<>();
//                for (int i = 0; i < list.size(); i++) {
//                    if (!keyList.contains(list.get(i))) {
//                        SelcetPostCartGoodsAttrs goodsAttrs = (SelcetPostCartGoodsAttrs) list.get(i);
//                        if (goodsAttrs.isSelected()) {
//                            lists.add(goodsAttrs.getItemGoodAttrs());  //所有选中的商品
//                        }
//                    }
//                }
//                for (int j = 0; j < datas.size(); j++) {
//                    PostcartAttrsCollection postcartAttrsCollection = datas.get(j);
//                    List<List<ItemGoodAttr>> selectGoodsAttrList = new ArrayList<>();
//                    List<SelcetPostCartGoodsAttrs> noselect = new ArrayList<>();
//                    for (int i = 0; i < postcartAttrsCollection.getGoodsAttrses().size(); i++) {
//                        List<ItemGoodAttr> itemGoodAttrs = postcartAttrsCollection.getGoodsAttrses().get(i).getItemGoodAttrs();
//                        if (lists.contains(itemGoodAttrs)) {
//                            selectGoodsAttrList.add(itemGoodAttrs);   //同一个店铺选中的商品
//                        }
//                        if (!lists.contains(itemGoodAttrs)) {
//                            noselect.add(postcartAttrsCollection.getGoodsAttrses().get(i));
//                        }
//                    }
//                    if (selectGoodsAttrList.size() == postcartAttrsCollection.getGoodsAttrses().size()) {
//                        int l = 0;
//                        for (int i = 0; i < list.size(); i++) {
//                            if (!keyList.contains(list.get(i))) {
//                                SelcetPostCartGoodsAttrs goodsAttrs = (SelcetPostCartGoodsAttrs) list.get(i);
//                                for (int k = 0; k < selectGoodsAttrList.size(); k++) {
//                                    if (goodsAttrs.getItemGoodAttrs().equals(selectGoodsAttrList.get(k))) {
//                                        list.remove(i);
//                                        i--;
//                                        l = i;
//                                    }
//                                }
//                            }
//                        }
//                        list.remove(l);
//                    }else if (selectGoodsAttrList.size() > 0 && noselect.size() > 0) {
//                        for (int i = 0; i < list.size(); i++) {
//                            if (!keyList.contains(list.get(i))) {
//                                SelcetPostCartGoodsAttrs goodsAttrs = (SelcetPostCartGoodsAttrs) list.get(i);
//                                for (int k = 0; k < selectGoodsAttrList.size(); k++) {
//                                    if (goodsAttrs.getItemGoodAttrs().equals(selectGoodsAttrList.get(k))) {
//                                        list.remove(i);
//                                        i--;
//                                    }
//                                }
//                            }
//                        }
//
//                        int storeNum = 0;
//                        for (int i = 0; i < noselect.size(); i++) {
//                            storeNum += Integer.parseInt(noselect.get(i).getGoodsnum());
//                        }
//                        for (int i = 0; i < list.size(); i++) {
//                            if (keyList.contains(list.get(i))) {
//                                ShopInfos shopInfos = (ShopInfos) list.get(i);
//                                if (postcartAttrsCollection.getShopInfos().getName().equals(shopInfos.getName())) {
//                                    shopInfos.setStoreNum(storeNum + "");
//                                }
//                            }
//                        }
//                        postCartAdapter = new RewardShoppingCartAdapter(context, this, list, keyList, handler);
//                        ptrListView.setAdapter(postCartAdapter);
//                    }
//                }
//                postCartAdapter.notifyDataSetChanged();
//                updateAmount();
                getData();
            } else if ("itemdel".equals(type)) {
                PostCartDel postCartDel = gson.fromJson(response, PostCartDel.class);
                MyApplication.getInstance().setSpValue(postCartDel.getSafeobj());
                showShortToast("删除成功,共删除购物车" + postCartDel.getItemNum() + "件条目");
                upDateNum();  //更新店铺的商品数
                if ((list.size() == position + 2) && keyList.contains(list.get(position - 1)) && amountofmaillist.contains(list.get(position + 1))) {
                    list.clear();
                } else if (keyList.contains(list.get(position - 1)) && amountofmaillist.contains(list.get(position + 1)) && keyList.contains(list.get(position + 2))) {
                    list.remove(position);
                    list.remove(position);
                    position--;
                    list.remove(position);
                    postCartAdapter = new RewardShoppingCartAdapter(context, this, list, keyList, amountofmaillist, handler);
                    ptrListView.setAdapter(postCartAdapter);
                } else {
                    if (!keyList.contains(list.get(position)) && !amountofmaillist.contains(list.get(position))) {
                        list.remove(position);
                        position--;
                        postCartAdapter = new RewardShoppingCartAdapter(context, this, list, keyList, amountofmaillist, handler);
                        ptrListView.setAdapter(postCartAdapter);
                    }
                }

                postCartAdapter.notifyDataSetChanged();
                updateAmount();
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    private void upDateNum() {
        SelcetPostCartGoodsAttrs goodsAttrs = (SelcetPostCartGoodsAttrs) list.get(position);
        for (String name : mapAll.keySet()) {
            List<SelcetPostCartGoodsAttrs> listItem = mapAll.get(name);
            int storeNum = 0;
            for (int i = 0; i < listItem.size(); i++) {
                if (!listItem.get(i).getItemGoodAttrs().equals(goodsAttrs.getItemGoodAttrs())) {
                    storeNum += Integer.parseInt(listItem.get(i).getGoodsnum());
                }
            }
            for (int j = 0; j < list.size(); j++) {
                if (keyList.contains(list.get(j))) {
                    ShopInfos shopInfos = (ShopInfos) list.get(j);
                    if (name.equals(shopInfos.getName())) {
                        shopInfos.setStoreNum(storeNum + "");
                    }
                }
            }
        }
    }

    @Override
    protected void ProcessFailResult(String response) {
        super.ProcessFailResult(response);
        Gson gson = new Gson();
        BaseResponse baseResponse = gson.fromJson(response, BaseResponse.class);
        if (baseResponse.getSafeobj() != null && !"".equals(baseResponse.getSafeobj())) {
            MyApplication.getInstance().setSpValue(baseResponse.getSafeobj());
        }
        ptrListView.onRefreshComplete();
        if (baseResponse.getCode() == 1001) {
            showShortToast("用户未登录,不能删除");
        } else if (baseResponse.getCode() == 1556) {
            showShortToast("未知错误，稍后重试");
        } else if (baseResponse.getCode() == 1666) {
            showShortToast("服务不可用，服务器异常");
        } else if (baseResponse.getCode() == 2005) {
            showShortToast("商品与 商品集合不匹配");
        } else if (baseResponse.getCode() == 2006) {
            showShortToast("商品集合数据格式错误");
        } else if (baseResponse.getCode() == 2007) {
            showShortToast("商品属性不在指定集合中");
        } else if (baseResponse.getCode() == 2008) {
            showShortToast("商品属性数据丢失，请管理员调整");
        } else if (baseResponse.getCode() == 2009) {
            showShortToast("商品属性选择不完整");
        } else if (baseResponse.getCode() == 2018) {
            showShortToast("购物车已存在该商品");
            popupWindow.dismiss();
            isRemove = false;
            popupWindow = null;
            if (!keyList.contains(list.get(position))) {
                list.remove(position);
                position--;
                postCartAdapter = new RewardShoppingCartAdapter(context, this, list, keyList, amountofmaillist, handler);
                ptrListView.setAdapter(postCartAdapter);
            }
            updataGoodNum();
            postCartAdapter.notifyDataSetChanged();
            updateAmount();
        }
    }

    private void updataGoodNum() {
        List<String> goodIdLists = new ArrayList<>();
        for (int i = 0; i < list.size(); i++) {
            if (!keyList.contains(list.get(i)) && !amountofmaillist.contains(list.get(i))) {
                SelcetPostCartGoodsAttrs goodsAttrs = (SelcetPostCartGoodsAttrs) list.get(i);
                goodIdLists.add(goodsAttrs.getGoodId());
            }
        }
        for (String name : mapAll.keySet()) {
            List<SelcetPostCartGoodsAttrs> listItem = mapAll.get(name);
            int storeNum = 0;
            for (int i = 0; i < listItem.size(); i++) {
                for (int j = 0; j < goodIdLists.size(); j++) {
                    if (goodIdLists.get(j).equals(listItem.get(i).getGoodId())) {
                        storeNum += Integer.parseInt(listItem.get(i).getGoodsnum());
                    }
                }
            }
            for (int j = 0; j < list.size(); j++) {
                if (keyList.contains(list.get(j))) {
                    ShopInfos shopInfos = (ShopInfos) list.get(j);
                    if (name.equals(shopInfos.getName())) {
                        shopInfos.setStoreNum(storeNum + "");
                    }
                }
            }
        }
    }

    private void initPopupWindow() {
        final Map<String, AttrItemBean> selectAttrMap = new HashMap<>();
        Handler handler = new Handler() {
            @Override
            public void handleMessage(Message msg) {
                super.handleMessage(msg);
                AttrItemBean attrItemBean = (AttrItemBean) msg.getData().getSerializable("attrItemBean");
                String attrId = attrItemBean.getAttrId();
                for (String attrKey : map.keySet()) {
                    List<String> list = map.get(attrKey);
                    for (int i = 0; i < list.size(); i++) {
                        if (attrId.equals(list.get(i))) {  //找到相应的key
                            if (selectAttrMap != null) {
                                if (selectAttrMap.size() > 0) {
                                    Iterator<String> iterator = selectAttrMap.keySet().iterator();
                                    while (iterator.hasNext()) {
                                        String next = iterator.next();
                                        AttrItemBean mapValue = selectAttrMap.get(next);
                                        if (mapValue.getAttrId().equals(attrId)) {   //去除属性
                                            iterator.remove();
                                            isRemove = true;
                                            break;
                                        }
                                    }
                                    if (isRemove) {  //去除属性
                                        if (selectAttrMap.size() > 0) {
                                            if (selectAttrMap.size() == 1) {
                                                Map.Entry<String, AttrItemBean> next = selectAttrMap.entrySet().iterator().next();
                                                String key = next.getKey();
                                                AttrItemBean value = next.getValue();
                                                List<String> canAttrs = getOnlyOneAttrCanSelect(value, key);
                                                itemAttrList = DataUtil.updataInfoUpgrade(itemAttrList, canAttrs, selectAttrMap);
                                                coinPostGoodAttrAdapter.notifyDataSetChanged();
                                                isRemove = false;
                                                getItemClickChangePic();
                                                return;
                                            } else {
                                                List<String> referList = getAllAlreadItemCanSelect(selectAttrMap);
                                                List<String> listStrings = getCompareStringList();
                                                referList.addAll(listStrings);
                                                itemAttrList = DataUtil.updataInfoUpgrade(itemAttrList, referList, selectAttrMap);
                                                coinPostGoodAttrAdapter.notifyDataSetChanged();
                                                isRemove = false;
                                                getItemClickChangePic();
                                                return;
                                            }
                                        } else {  //无点击,恢复正常
                                            itemAttrList = DataUtil.updataAdapter(itemAttrList);
                                            coinPostGoodAttrAdapter.notifyDataSetChanged();
                                            selectAttrMap.clear();
                                            isRemove = false;
                                            getItemClickChangePic();
                                            return;
                                        }
                                    } else {  //不去除属性
                                        for (String selectKey : selectAttrMap.keySet()) {
                                            if (attrKey.equals(selectKey)) {  //同一类点击切换
                                                isSameAttrKey = true;
                                                break;
                                            }
                                        }
                                        if (isSameAttrKey) {  //同一类点击切换
                                            if (selectAttrMap.size() == 1) {
                                                selectAttrMap.clear();
                                                selectAttrMap.put(attrKey, attrItemBean);
                                                List<String> canAttrs = getOnlyOneAttrCanSelect(attrItemBean, attrKey);
                                                itemAttrList = DataUtil.updataInfoUpgrade(itemAttrList, canAttrs, selectAttrMap);
                                                coinPostGoodAttrAdapter.notifyDataSetChanged();
                                                getItemClickChangePic();
                                                isSameAttrKey = false;
                                                return;
                                            } else {
                                                selectAttrMap.put(attrKey, attrItemBean);
                                                List<String> referList = getAllAlreadItemCanSelect(selectAttrMap);
                                                List<String> listStrings = getCompareStringList();
                                                referList.addAll(listStrings);
                                                itemAttrList = DataUtil.updataInfoUpgrade(itemAttrList, referList, selectAttrMap);
                                                coinPostGoodAttrAdapter.notifyDataSetChanged();
                                                getItemClickChangePic();
                                                isSameAttrKey = false;
                                                return;
                                            }
                                        } else {  //不同类的属性点击
                                            selectAttrMap.put(attrKey, attrItemBean);
                                            List<String> referList = getAllAlreadItemCanSelect(selectAttrMap);
                                            List<String> listStrings = getCompareStringList();
                                            referList.addAll(listStrings);
                                            itemAttrList = DataUtil.updataInfoUpgrade(itemAttrList, referList, selectAttrMap);
                                            coinPostGoodAttrAdapter.notifyDataSetChanged();
                                            getItemClickChangePic();
                                            isSameAttrKey = false;
                                            return;
                                        }
                                    }
                                } else {
                                    selectAttrMap.put(attrKey, attrItemBean);
                                    List<String> canAttrs = getOnlyOneAttrCanSelect(attrItemBean, attrKey);
                                    itemAttrList = DataUtil.updataInfoUpgrade(itemAttrList, canAttrs, selectAttrMap);
                                    coinPostGoodAttrAdapter.notifyDataSetChanged();
                                    getItemClickChangePic();
                                    return;
                                }
                            }
                        }
                    }
                }
            }

            @NonNull
            private List<String> getCompareStringList() {
                List<List<String>> compareOtherList = new ArrayList<>();
                for (String strKey : selectAttrMap.keySet()) {
                    Map<String, AttrItemBean> secordMap = new HashMap<>();
                    for (String secordKey : selectAttrMap.keySet()) {
                        if (!secordKey.equals(strKey)) {
                            secordMap.put(secordKey, selectAttrMap.get(secordKey));
                        }
                    }
                    List<String> secordItemList = getAllAlreadItemCanSelect(secordMap);
                    List<String> singleList = getSingleList(strKey);
                    List<String> itemAttrsList = new ArrayList<>();
                    for (int j = 0; j < secordItemList.size(); j++) {
                        if (singleList.contains(secordItemList.get(j))) {
                            itemAttrsList.add(secordItemList.get(j));
                        }
                    }
                    compareOtherList.add(itemAttrsList);
                }
                return getListStrings(compareOtherList);
            }

            @NonNull
            private List<String> getSingleList(String attrKey) {
                int indexInList = DataUtil.indexInList(attrKeyList, attrKey);
                List<String> singleList = new ArrayList<>();
                List<AttrItemBean> attrItemBeens = itemAttrList.get(indexInList);
                for (int j = 0; j < attrItemBeens.size(); j++) {
                    AttrItemBean itemBean = attrItemBeens.get(j);
                    singleList.add(itemBean.getAttrId());
                }
                return singleList;
            }

            private void getItemClickChangePic() {
                if (selectAttrMap != null && selectAttrMap.size() > 0) {
                    List<String> listId = new ArrayList<>();
                    for (String strKey : selectAttrMap.keySet()) {
                        AttrItemBean itemBean = selectAttrMap.get(strKey);
                        listId.add(itemBean.getAttrId());
                    }
                    List<GoodsAttrCollections> collectioneList = new ArrayList<>();
                    for (GoodsAttrCollections goodAttr : attrCollectionses) {
                        List<String> attrs = goodAttr.getAttrs();
                        if (attrs.containsAll(listId)) {
                            collectioneList.add(goodAttr);
                        }
                    }
                    if (collectioneList.get(0).getPrice() != null && !"".equals(collectioneList.get(0).getPrice())) {
                        tv_edit_price.setText(collectioneList.get(0).getPrice() + " 元");
                    } else {
                        tv_edit_price.setText("0 元");
                    }
                    switch (item.getGoodstype()) {
                        case "1":
                            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                                tv_edit_md.setText(Html.fromHtml("<font color='#ff7f00'>" + context.getResources().getString(R.string.give_meidou) +
                                        CommonTool.getWhole(collectioneList.get(0).getPrice()) + "美豆+</font><font color='#ff4c4c'>" + DataUtil.multiplys(collectioneList.get(0).getPrice(), "0.05", 2) + "红豆<font>", Html.FROM_HTML_MODE_COMPACT));
                            } else {
                                tv_edit_md.setText(Html.fromHtml("<font color='#ff7f00'>" + context.getResources().getString(R.string.give_meidou) +
                                        CommonTool.getWhole(collectioneList.get(0).getPrice()) + "美豆+</font><font color='#ff4c4c'>" + DataUtil.multiplys(collectioneList.get(0).getPrice(), "0.05", 2) + "红豆<font>"));
                            }
//                            tv_edit_hd.setText("");
                            break;
//                        case "2":
//                            tv_edit_md.setText("立即赠: " + DataUtil.multiplys(collectioneList.get(0).getPrice(), "2") + " 美豆");
//                            tv_edit_hd.setText("");
//                            break;
                        case "3":
                            tv_edit_md.setText(context.getResources().getString(R.string.award_hongdou) + collectioneList.get(0).getPrice() + " 红豆");
                            tv_edit_md.setTextColor(context.getResources().getColor(R.color.title_red));
//                            tv_edit_hd.setText("分期奖 " + collectioneList.get(0).getPrice() + " 红豆");
                            break;
                    }
                    if (collectioneList.get(0).getStocknum() != null && !"".equals(collectioneList.get(0).getStocknum())) {
                        tvInventory.setText("库存：" + collectioneList.get(0).getStocknum() + " 件");
                    } else {
                        tvInventory.setText("库存：0 件");
                    }
                    Glide.with(context).load(Url.IMG_URL + collectioneList.get(0).getThumbnail()).placeholder(R.mipmap.iv_eg).diskCacheStrategy(DiskCacheStrategy.SOURCE).into(ivImg);
                } else {
                    tvInventory.setText("库存：999 件");
                }
            }

            @NonNull
            private List<String> getOnlyOneAttrCanSelect(AttrItemBean attrItemBean, String selectKey) {
                ArrayList<String> canSelects = getItemCanSelectAttr(attrItemBean);
                List<String> oneSelectCanAttr = new ArrayList<>();
                List<String> canAttrs = new ArrayList<>();
                for (String str : mapAllAttrs.keySet()) {
                    if (str.equals(selectKey)) {
                        List<AttrItemBean> attrItemBeenList = mapAllAttrs.get(str);
                        for (int j = 0; j < attrItemBeenList.size(); j++) {
                            oneSelectCanAttr.add(attrItemBeenList.get(j).getAttrId());
                        }
                    }
                }
                oneSelectCanAttr.addAll(canSelects);
                Set set = new HashSet();
                for (String str : oneSelectCanAttr) {
                    if (set.add(str)) {
                        canAttrs.add(str);  //去重后的可选的属性
                    }
                }
                return canAttrs;
            }

            @NonNull
            private List<String> getAllAlreadItemCanSelect(Map<String, AttrItemBean> selectAttrMap) {
                List<String> temporaryAttrId = new ArrayList<>();
                for (String str : selectAttrMap.keySet()) {
                    AttrItemBean attrBean = selectAttrMap.get(str);
                    temporaryAttrId.add(attrBean.getAttrId());
                }
                List<List<String>> collectionses = new ArrayList<>();
                for (GoodsAttrCollections goodAttr : attrCollectionses) {
                    List<String> attrs = goodAttr.getAttrs();
                    if (attrs.containsAll(temporaryAttrId)) {
                        collectionses.add(attrs);
                    }
                }
//                referList.addAll(collectionses.get(0));
//                for (int j = 0; j < collectionses.size(); j++) {
//                    referList.retainAll(collectionses.get(j));    //多数组取交集
//                }
                List<String> referList = getListStrings(collectionses);
                return referList;
            }

            @NonNull
            private List<String> getListStrings(List<List<String>> collectionses) {
                List<String> referList = new ArrayList<>();
                Set set = new HashSet();
                for (int i = 0; i < collectionses.size(); i++) {
                    List<String> list = collectionses.get(i);
                    for (int j = 0; j < list.size(); j++) {
                        if (set.add(list.get(j))) {
                            referList.add(list.get(j));
                        }
                    }
                }
                return referList;
            }

            @NonNull
            private ArrayList<String> getItemCanSelectAttr(AttrItemBean attrItemBean) {
                List<List<String>> collectionses = new ArrayList<>();
                for (GoodsAttrCollections goodAttr : attrCollectionses) {
                    if (goodAttr.getAttrs().contains(attrItemBean.getAttrId())) {
                        collectionses.add(goodAttr.getAttrs());
                    }
                }
                Set set = new HashSet();
                ArrayList<String> canSelects = new ArrayList<>();
                for (List<String> collection : collectionses) {
                    for (String attr : collection) {
                        if (set.add(attr)) {
                            canSelects.add(attr);
                        }
                    }
                }
                return canSelects;
            }
        };
        popupWindow_view = getActivity().getLayoutInflater().inflate(R.layout.reward_post_cart_info, null);
        popupWindow = new PopupWindow(popupWindow_view, LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);
        ivImg = (ImageView) popupWindow_view.findViewById(R.id.ivImg);
        TextView tvName = (TextView) popupWindow_view.findViewById(R.id.tvName);
        ImageView ivCancel = (ImageView) popupWindow_view.findViewById(R.id.ivCancel);
        tvInventory = (TextView) popupWindow_view.findViewById(R.id.tvInventory);
        tvPostage = (TextView) popupWindow_view.findViewById(R.id.tvPostage);
        tv_edit_price = (TextView) popupWindow_view.findViewById(R.id.tv_edit_price);
        tv_edit_hd = (TextView) popupWindow_view.findViewById(R.id.tv_edit_hd);
        tv_edit_md = (TextView) popupWindow_view.findViewById(R.id.tv_edit_md);
        ListView lvList = (ListView) popupWindow_view.findViewById(R.id.lvList);
        TextView tvAddSure_attr = (TextView) popupWindow_view.findViewById(R.id.tvAddSure_attr);
        RelativeLayout rl_ctx = (RelativeLayout) popupWindow_view.findViewById(R.id.rl_ctx);
        WindowManager manger = (WindowManager) getActivity().getSystemService(ShoppingCartActivity.WINDOW_SERVICE);
        Display display = manger.getDefaultDisplay();
        ViewGroup.LayoutParams layoutParams = rl_ctx.getLayoutParams();
        layoutParams.height = 3 * display.getHeight() / 4;
        if (item.getPrice() != null && !"".equals(item.getPrice())) {
            tv_edit_price.setText(item.getPrice() + " 元");

        }
        switch (item.getGoodstype()) {
            case "1":
                if (DataUtil.moreThanZero(item.getPrice())) {
                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                        tv_edit_md.setText(Html.fromHtml("<font color='#ff7f00'>" + context.getResources().getString(R.string.give_meidou) +
                                CommonTool.getWhole(item.getPrice()) + "美豆</font><font color='#ff4c4c'>/" + context.getResources().getString(R.string.more_give) + DataUtil.multiplys(item.getPrice(), "0.05", 2) + "红豆<font>", Html.FROM_HTML_MODE_COMPACT));
                    } else {
                        tv_edit_md.setText(Html.fromHtml("<font color='#ff7f00'>" + context.getResources().getString(R.string.give_meidou) +
                                CommonTool.getWhole(item.getPrice()) + "美豆</font><font color='#ff4c4c'>/" + context.getResources().getString(R.string.more_give) + DataUtil.multiplys(item.getPrice(), "0.05", 2) + "红豆<font>"));
                    }
                } else {
                    tv_edit_md.setText("");
                }
                break;
//            case "2":
//                tv_edit_md.setText("立即赠: " + DataUtil.multiplys(item.getPrice(), "2") + " 美豆");
//                tv_edit_hd.setText("");
//                break;
            case "3":
                tv_edit_md.setText(context.getResources().getString(R.string.award_hongdou) + item.getPrice() + " 红豆");
                tv_edit_md.setTextColor(context.getResources().getColor(R.color.title_red));
//                tv_edit_hd.setText("分期奖 " + item.getPrice() + " 红豆");
                break;
        }
        if (item.getStocknum() != null && !"".equals(item.getStocknum())) {
            tvInventory.setText("库存：" + item.getStocknum() + " 件");
        } else {
            tvInventory.setText("库存：0 件");
        }

        try {
            JSONObject js = new JSONObject(goodsInfoObject.optString(item.getGoodsid()));
            String postage = js.optString("postage");
            if (postage != null && DataUtil.moreThanZero(postage)) {
                tvPostage.setText("运费：" + postage + "元");
            } else {
                tvPostage.setText("");
            }

        } catch (JSONException e) {
            e.printStackTrace();
        }

        Glide.with(this).load(Url.IMG_URL + item.getImgUrl()).placeholder(R.mipmap.iv_eg).diskCacheStrategy(DiskCacheStrategy.SOURCE).into(ivImg);
        if (item.getStatus().equals("1")) {
            tvAddSure_attr.setOnClickListener(new View.OnClickListener() {
                private boolean containsAll;
                private boolean b;

                @Override
                public void onClick(View view) {
                    if (selectAttrMap.size() > 0) {
                        List<String> keySelect = new ArrayList<>();
                        List<String> attrIdList = new ArrayList<String>();
                        for (String attr : selectAttrMap.keySet()) {
                            keySelect.add(attr);
                            AttrItemBean attrItemBean = selectAttrMap.get(attr);
                            attrIdList.add(attrItemBean.getAttrId());
                        }
                        if (allList != null && allList.size() > 0) {
                            for (int j = 0; j < allList.size(); j++) {
                                AttrsSelect attrsSelect = allList.get(j);
                                Map<String, List<String>> map = attrsSelect.getItemMaps();
                                List<String> mapList = new ArrayList<String>();
                                List<String> mapValue = new ArrayList<String>();
                                for (String attr2 : map.keySet()) {
                                    mapList.add(attr2);
                                    List<String> list = map.get(attr2);
                                    mapValue.addAll(list);
                                }
                                b = DataUtil.equalList(keySelect, mapList);
                                containsAll = mapValue.containsAll(attrIdList);
                                if (b && containsAll) {
                                    List<ItemGoodAttr> itemGoodAttrs = item.getItemGoodAttrs();
                                    itemGoodAttrs.clear();
                                    for (String str : selectAttrMap.keySet()) {
                                        AttrItemBean attrItemBean = selectAttrMap.get(str);
                                        ItemGoodAttr itemGoodAttr = new ItemGoodAttr();
                                        itemGoodAttr.setAttrk(str);
                                        itemGoodAttr.setAttrv(attrItemBean.getName());
                                        itemGoodAttr.setId(attrItemBean.getAttrId());
                                        itemGoodAttrs.add(itemGoodAttr);
                                    }
                                    item.setPrice(attrsSelect.getPrice());
                                    item.setImgUrl(attrsSelect.getThumbnail());
                                    item.setAttrcollection(attrsSelect.getId());
                                    item.setBacksilvernum(attrsSelect.getBacksilvernum());
                                    String str = "[";
                                    for (ItemGoodAttr attr : itemGoodAttrs) {
                                        str += "\"" + attr.getId() + "\",";
                                    }
                                    String json = str.substring(0, str.length() - 1) + "]";
                                    getEditAttrs(item.getGoodId(), item.getGoodsid(), json, item.getAttrcollection());
                                    postCartAdapter.notifyDataSetChanged();
                                    if (item.isSelected()) {
                                        updateAmount();
                                    }
                                    return;
                                }
                            }
                        }
                        if (!(b && containsAll)) {
                            Toast.makeText(context, "请您选择完整的商品属性,本次编辑无效", Toast.LENGTH_SHORT).show();
                        }
                    } else {
                        if (popupWindow != null && popupWindow.isShowing()) {
                            popupWindow.dismiss();
                            isRemove = false;
                            popupWindow = null;
                        }
                    }
                }
            });
        } else {
            showShortToast("该店铺停业休整,店铺商品不能编辑");
        }
        tvName.setText(item.getName());
        coinPostGoodAttrAdapter = new CoinPostGoodAttrAdapter(context, handler, keyLists, itemAttrList);
        lvList.setAdapter(coinPostGoodAttrAdapter);
        coinPostGoodAttrAdapter.notifyDataSetChanged();
        ivCancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (popupWindow != null && popupWindow.isShowing()) {
                    popupWindow.dismiss();
                    isRemove = false;
                    popupWindow = null;
                }
            }
        });
        if (!popupWindow.isShowing()) {
            isRemove = false;
        }
        popupWindow.setBackgroundDrawable(new ColorDrawable(0));
        popupWindow_view.measure(View.MeasureSpec.UNSPECIFIED, View.MeasureSpec.UNSPECIFIED);
        int[] location = new int[2];
        relaBottom.getLocationOnScreen(location);
        popupWindow.showAtLocation(relaBottom, Gravity.BOTTOM, location[0], location[1] - popupWindow.getHeight());
        WindowManager.LayoutParams lp = getActivity().getWindow().getAttributes();
        lp.alpha = 0.3f;
        getActivity().getWindow().setAttributes(lp);
        popupWindow.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {
                WindowManager.LayoutParams lp = getActivity().getWindow().getAttributes();
                lp.alpha = 1f;
                getActivity().getWindow().setAttributes(lp);
            }
        });
    }

    private void getEditAttrs(String cartid, String goodsid, String attrlist, String collectionid) {
        Map<String, String> map = new HashMap<>();
        map.put("cartid", cartid);
        map.put("goodsid", goodsid);
        map.put("attrlist", attrlist);
        map.put("collectionid", collectionid);
        type = "editcart";
        getServer(Url.REWARD_EDIT_POST_SHOPPING_ATTR, map, "", false, null, "post");
    }

    public void updateStoreNum() {
        SelcetPostCartGoodsAttrs goodsAttrs = (SelcetPostCartGoodsAttrs) list.get(position);
        for (String name : mapAll.keySet()) {
            List<SelcetPostCartGoodsAttrs> listItem = mapAll.get(name);
            int storeNum = 0;
            for (int i = 0; i < listItem.size(); i++) {
                if (listItem.get(i).getItemGoodAttrs().equals(goodsAttrs.getItemGoodAttrs())) {
                    storeNum += Integer.parseInt(goodsAttrs.getGoodsnum());
                }
                if (!listItem.get(i).getItemGoodAttrs().equals(goodsAttrs.getItemGoodAttrs())) {
                    storeNum += Integer.parseInt(listItem.get(i).getGoodsnum());
                }
            }
            for (int j = 0; j < list.size(); j++) {
                if (keyList.contains(list.get(j))) {
                    ShopInfos shopInfos = (ShopInfos) list.get(j);
                    if (name.equals(shopInfos.getName())) {
                        shopInfos.setStoreNum(storeNum + "");
                    }
                }
            }
        }
        postCartAdapter.notifyDataSetChanged();
    }

    public String updateAmount() {
        String str = "{";
        String price = "0.00";
        String totalPostage = "0.00";
        String md = "0.00";
        String hd = "0.00";
        selectGoodsList.clear();
        for (int i = 0; i < list.size(); i++) {
            if (!keyList.contains(list.get(i)) && !amountofmaillist.contains(list.get(i))) {
                SelcetPostCartGoodsAttrs goodsAttrs = (SelcetPostCartGoodsAttrs) list.get(i);
                if (goodsAttrs.isSelected()) {
                    selectGoodsList.add(goodsAttrs);
                    str += "\"" + goodsAttrs.getGoodId() + "\":\"" + goodsAttrs.getGoodsnum() + "\",";
                    price = DataUtil.add(price, DataUtil.multiplys(goodsAttrs.getPrice(), goodsAttrs.getGoodsnum(), 2));
                    switch (goodsAttrs.getGoodstype()) {
                        case "1":
                            md = DataUtil.add(md, DataUtil.multiplys(goodsAttrs.getPrice(), goodsAttrs.getGoodsnum(), 2));
                            break;
                      /*  case "2":
                            md = DataUtil.add(md, DataUtil.multiplys(DataUtil.multiplys(goodsAttrs.getPrice(), goodsAttrs.getGoodsnum()), "2"));
                            break;*/
                        case "3":
//                            md = DataUtil.add(md, DataUtil.multiplys(goodsAttrs.getPrice(), goodsAttrs.getGoodsnum()));
                            hd = DataUtil.add(hd, DataUtil.multiplys(goodsAttrs.getPrice(), goodsAttrs.getGoodsnum(), 2));
                            break;
                    }
                }
            }
        }
        if (selectGoodsList != null && selectGoodsList.size() > 0) {  //所有选中的商品
            ArrayList<PostcartAttrsCollection> collectionList = new ArrayList<>();
            for (int j = 0; j < datas.size(); j++) {
                PostcartAttrsCollection postcartAttrsCollection = datas.get(j);
                List<SelcetPostCartGoodsAttrs> selectGoodsAttrList = new ArrayList<>();
                for (int i = 0; i < postcartAttrsCollection.getGoodsAttrses().size(); i++) {
                    SelcetPostCartGoodsAttrs goodsAttrs = postcartAttrsCollection.getGoodsAttrses().get(i);
                    if (selectGoodsList.contains(goodsAttrs)) {
                        selectGoodsAttrList.add(goodsAttrs);   //同一个店铺选中的商品
                    }
                }
                if (selectGoodsAttrList.size() > 0) {
                    if (postcartAttrsCollection.getGoodsAttrses().containsAll(selectGoodsAttrList)) {
                        PostcartAttrsCollection attrsCollection = new PostcartAttrsCollection();
                        attrsCollection.setShopInfos(postcartAttrsCollection.getShopInfos());
                        attrsCollection.setGoodsAttrses(selectGoodsAttrList);
                        collectionList.add(attrsCollection);
                    }
                }
            }
            for (int i = 0; i < collectionList.size(); i++) {
                PostcartAttrsCollection postcartAttrsCollection = collectionList.get(i);
                List<Integer> list = new ArrayList<>();
                String sameShopTotalPrice = "0.00";
                for (int j = 0; j < postcartAttrsCollection.getGoodsAttrses().size(); j++) {
                    list.add(Integer.parseInt(postcartAttrsCollection.getGoodsAttrses().get(j).getPostage()));
                    sameShopTotalPrice = DataUtil.add(DataUtil.multiplys(postcartAttrsCollection.getGoodsAttrses().get(j).getPrice(),
                            postcartAttrsCollection.getGoodsAttrses().get(j).getGoodsnum(), 2), sameShopTotalPrice);
                }
                if (postcartAttrsCollection.getShopInfos().getAmountofmail() != null &&
                        !"".equals(postcartAttrsCollection.getShopInfos().getAmountofmail()) && DataUtil.moreThanZero(postcartAttrsCollection.getShopInfos().getAmountofmail())) {
                    if (DataUtil.moreThanOther(sameShopTotalPrice, postcartAttrsCollection.getShopInfos().getAmountofmail())) {
                        totalPostage = DataUtil.add(totalPostage, "0.00");  //免邮费
                    } else {
                        totalPostage = DataUtil.add(totalPostage, DataUtil.maxInteger(list) + "");
                    }
                } else {
                    totalPostage = DataUtil.add(totalPostage, DataUtil.maxInteger(list) + "");
                }
            }
        }

        tvRewardPrice.setText(DataUtil.add(price, totalPostage) + " 元");
        if (DataUtil.moreThanZero(hd) && DataUtil.moreThanZero(md)) {
            tvHd.setText(context.getResources().getString(R.string.award_hongdou) + hd + "红豆");
            tvHd.setTextColor(context.getResources().getColor(R.color.title_red));
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                tvMd.setText(Html.fromHtml("<font color='#ff7f00'>" + context.getResources().getString(R.string.give_meidou) +
                        CommonTool.getWhole(md) + "美豆</font><font color='#ff4c4c'>/" + context.getResources().getString(R.string.more_give) + DataUtil.multiplys(md, "0.05", 2) + "红豆<font>", Html.FROM_HTML_MODE_COMPACT));
            } else {
                tvMd.setText(Html.fromHtml("<font color='#ff7f00'>" + context.getResources().getString(R.string.give_meidou) +
                        CommonTool.getWhole(md) + "美豆</font><font color='#ff4c4c'>/" + context.getResources().getString(R.string.more_give) + DataUtil.multiplys(md, "0.05", 2) + "红豆<font>"));
            }
        } else if (!DataUtil.moreThanZero(hd) && DataUtil.moreThanZero(md)) {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                tvHd.setText(Html.fromHtml("<font color='#ff7f00'>" + context.getResources().getString(R.string.give_meidou) +
                        CommonTool.getWhole(md) + "美豆</font><font color='#ff4c4c'>/" + context.getResources().getString(R.string.more_give) + DataUtil.multiplys(md, "0.05", 2) + "红豆<font>", Html.FROM_HTML_MODE_COMPACT));
            } else {
                tvHd.setText(Html.fromHtml("<font color='#ff7f00'>" + context.getResources().getString(R.string.give_meidou) +
                        CommonTool.getWhole(md) + "美豆</font><font color='#ff4c4c'>/" + context.getResources().getString(R.string.more_give) + DataUtil.multiplys(md, "0.05", 2) + "红豆<font>"));
            }
            tvMd.setText("");
        } else if (DataUtil.moreThanZero(hd) && !DataUtil.moreThanZero(md)) {
            tvHd.setText(context.getResources().getString(R.string.award_hongdou) + hd + "红豆");
            tvHd.setTextColor(context.getResources().getColor(R.color.title_red));
            tvMd.setText("");
        } else {
            tvHd.setText(context.getResources().getString(R.string.award_hongdou) + "0.00 红豆");
            tvHd.setTextColor(context.getResources().getColor(R.color.title_red));
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                tvMd.setText(Html.fromHtml("<font color='#ff7f00'>" + context.getResources().getString(R.string.give_meidou) +
                        "0美豆</font><font color='#ff4c4c'>/" + context.getResources().getString(R.string.more_give) + "0.00红豆<font>", Html.FROM_HTML_MODE_COMPACT));
            } else {
                tvMd.setText(Html.fromHtml("<font color='#ff7f00'>" + context.getResources().getString(R.string.give_meidou) +
                        "0美豆</font><font color='#ff4c4c'>/" + context.getResources().getString(R.string.more_give) + "0.00红豆<font>"));
            }
        }
        if (DataUtil.moreThanZero(totalPostage)) {
            tvTotalPostage.setText("快递: " + totalPostage + " 元");
        } else {
            tvTotalPostage.setText("");
        }
        if (list != null && list.size() > 0) {
            return str.substring(0, str.length() - 1) + "}";
        } else {
            return "";
        }
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == RESULTACCOUNTS) {
            if (list != null && list.size() > 0) {
                for (int i = 0; i < list.size(); i++) {
                    if (!keyList.contains(list.get(i)) && !amountofmaillist.contains(list.get(i))) {
                        SelcetPostCartGoodsAttrs goodsAttrs = (SelcetPostCartGoodsAttrs) list.get(i);
                        goodsAttrs.setSelected(false);
                    }
                }
                postCartAdapter.notifyDataSetChanged();
                updateAmount();
            }
        }
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        ButterKnife.unbind(this);
    }

    public void setDetailDatas() {
        String str = "";
        for (int i = 0; i < list.size(); i++) {
            if (!keyList.contains(list.get(i)) && !amountofmaillist.contains(list.get(i))) {
                SelcetPostCartGoodsAttrs goodsAttrs = (SelcetPostCartGoodsAttrs) list.get(i);
                if (goodsAttrs.isSelected()) {
                    str += goodsAttrs.getGoodId() + ",";
                }
            }
        }
        if (!"".equals(str) && !",".equals(str)) {
            Map<String, String> map = new HashMap<>();
            map.put("cartids", str.substring(0, str.length() - 1));
            type = "del";
            getServer(Url.DELETE_CART, map, "", false, null, "post");
        } else {
            showShortToast("请选择商品");
        }
    }

    public void detail() {
        if (!keyList.contains(list.get(position))) {
            SelcetPostCartGoodsAttrs goodsAttrs = (SelcetPostCartGoodsAttrs) list.get(position);
            Map<String, String> map = new HashMap<>();
            map.put("cartids", goodsAttrs.getGoodId());
            type = "itemdel";
            getServer(Url.DELETE_CART, map, "", false, null, "post");
        }
    }
}
